package com.base.cn.platform.os.controller.integragoods;

import com.base.cn.platform.os.common.AdminBaseController;
import com.base.cn.platform.os.common.log.aop.AdminModuleEnum;
import com.base.cn.platform.os.common.log.aop.OpLog;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.course.CourseType;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.user.UserExpandFrom;
import com.base.cn.platform.os.entity.integralgood.*;
import com.base.cn.platform.os.service.manage.integralgood.IntegralCardVoucherService;
import com.base.cn.platform.os.service.manage.integralgood.IntegralGoodService;
import com.base.cn.platform.os.service.manage.integralgood.IntegralVirtualGoodService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 积分虚拟商品卡密
 * @Author: Hello豆包
 * @Date: 2019/10/18 9:32
 */
@Controller
@RequestMapping("/admin/IntegralCardVoucher")
public class IntegralCardVoucherController extends AdminBaseController {
    @Autowired
    private Environment environment;
    @Autowired
     private   IntegralCardVoucherService integralCardVoucherService;
    @Autowired
    private IntegralVirtualGoodService integralVirtualGoodService;



    /**
     * 虚拟商品列表
     * @return
     */
    @RequestMapping("virtual/goodList")
    public String goodList(Model model){
        return resultPage("/integralgood/virtual/virtual_good");
    }


    /**
     * 积分兑换商品列表
     * @return
     */
    @RequestMapping("openInfo")
    public  String openInfo(Model model,@RequestParam(value = "id") BigDecimal id){
        Map map = integralVirtualGoodService.getById(id);
        model.addAttribute("entity",map);
        return  resultPage("/integralgood/virtual/virtual_info");
    }


    /**
     * 虚拟商品卡券表
     * @return
     */
    @RequestMapping("virtual/getPageIntegralCardVoucher")
    public  String getCardPageList(Model model,@RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage , @RequestBody IntegralCardVoucherExpand integralVirtualGood){
        integralVirtualGood.setSetUserData(true);
        Map map = integralCardVoucherService.getPageList(currentPage,integralVirtualGood);
        model.addAttribute("dataMap",map);
        return  resultPage("/integralgood/virtual/virual_info_ajax_list");
    }


    /**
     * 虚拟商品列表
     * @return
     */
    @RequestMapping("/virtual/goodAjaxList")
    public String goodAjaxList(Model model ,@RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage , @RequestBody IntegralVirtualGood integralVirtualGood){
        Map pageList = integralVirtualGoodService.getPageList(currentPage, integralVirtualGood);
        model.addAttribute("dataMap",pageList);
        return resultPage("/integralgood/virtual/virtual_good_ajax");
    }
    /**
     * 虚拟商品列表
     * @return
     */
    @RequestMapping("/virtual/selectGoodAjaxList")
    public String selectGoodAjaxList(Model model ,@RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage , @RequestBody IntegralVirtualGoodExpand integralVirtualGood){
        integralVirtualGood.setStatus(1);
        Map pageList = integralVirtualGoodService.getPageList(currentPage, integralVirtualGood);
        model.addAttribute("dataMap",pageList);
        return resultPage("/integralgood/virtual/select_virtual_good_ajax");
    }

    /**
     * 导入页面
     * @param model
     * @return
     */
    @RequestMapping("initImportExcels")
    public String initImportExcels(Model model){
    return resultPage("/integralgood/IntegraCardImport");
    }

    /**
     * 导入数据
     * @param request
     * @param file
     * @return
     */
    @RequestMapping(value = "/ajaxImportExcel",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public Map<String,Object>  importExcels(HttpServletRequest request,
                                                @RequestPart(value = "file") MultipartFile file ){

        String referer = request.getHeader("referer");
        if(!StringUtils.isNotEmpty(referer)){
            return ResultUtil.SUCCESS(null,"非法请求，上传失败");
        }
        String shopName = request.getParameter("shopName");

        HSSFWorkbook wookbook = null;
        try {
            wookbook = new HSSFWorkbook(file.getInputStream());
        } catch (Exception e) {
            return ResultUtil.SUCCESS(null,"读取xls表格数据错误");
        }
        //只读取sheet1
        HSSFSheet sheet = wookbook.getSheetAt(0);
        //excel中实际行数
        int rows = sheet.getPhysicalNumberOfRows();
        if (rows == 0) {
            return ResultUtil.SUCCESS(null,"xls表格中没有填写数据");
        }
        if (rows > 1001) {
            return ResultUtil.SUCCESS(null,"xls表中的数据不能多于1000行");
        }
        //验证数据
        Map<String, Object> checkResult = checkExcelData(sheet);
            if(ObjectUtils.isNotEmpty(checkResult)){

                    if(!ResultUtil.getSuccess(checkResult)){
                        return  checkResult;
                    }else{
                        List<IntegralCardVoucher>  list = (List<IntegralCardVoucher>) ResultUtil.getEntity(checkResult);
                        integralCardVoucherService.saveListEntity(list,shopName);
                    }
            }else{
                return ResultUtil.ERROR("导入失败");
            }
        return ResultUtil.SUCCESS("导入成功");
    }




    /**
     * 校验excel表格所有信息
     * @param sheet
     * @return
     */
    public Map<String, Object> checkExcelData(HSSFSheet sheet) {
        List<IntegralCardVoucher>  list = new ArrayList<>();

        int rows = sheet.getPhysicalNumberOfRows();
        for (int i = 1; i <= rows; i++) {
            // 读取行为第二行开始
            HSSFRow row = sheet.getRow(i);
            if (row != null) {
                // 如果是空行直接跳过
                Iterator<Cell> it = row.iterator();
                boolean isBlank = true;
                while (it.hasNext() && isBlank) {
                    Cell c = it.next();
                    c.setCellType(CellType.STRING);
                    if (c.getCellType() == HSSFCell.CELL_TYPE_BLANK || StringUtils.isEmpty(c.getStringCellValue())) {
                        continue;
                    }
                    isBlank = false;
                }
                if (isBlank) {
                    continue;
                }

                try {
                    row.getPhysicalNumberOfCells();
                    // **读取行中的列**
                    //账号
                    HSSFCell cell = row.getCell((short) 0);
                    String account = null;
                    if (cell != null) {
                        cell.setCellType(CellType.STRING);
                        account = cell.getStringCellValue().trim();
                    }

                    // 获取并校验账号格式, 校验通过存入map, 准备唯一性校验
                    cell = row.getCell((short) 1);
                    String camilo = null;
                    if (cell != null) {
                        cell.setCellType(CellType.STRING);
                        camilo = cell.getStringCellValue().trim();
                    }
                    if(StringUtils.isEmpty(camilo)&&StringUtils.isEmpty(account)){
                        continue;
                    }
                    if(StringUtils.isEmpty(account)){
                        return  ResultUtil.ERROR("第"+i+"行的账号为空");
                    }
                    if(StringUtils.isEmpty(camilo)){
                        return  ResultUtil.ERROR("第"+i+"行的密码为空");
                    }
                    IntegralCardVoucher integralCardVoucher = new IntegralCardVoucher();
                    integralCardVoucher.setAccount(account);
                    integralCardVoucher.setCamilo(camilo);
                    list.add(integralCardVoucher);
                } catch (Exception e) {

                    it.remove();
                    continue;
                }
            }
        }
        if(ObjectUtils.isNotEmpty(list)){
            return   ResultUtil.SUCCESS(list);
        }else{
            return  null;
        }

    }
    /**
     * 下载模板
     * @return ResponseEntity<byte[]>
     */
    @RequestMapping("/downloadTemplate")
    public ResponseEntity<byte[]> downloadTemplate() throws Exception{
        return this.getTempFile();
    }

    /**
     * 获取模板文件
     * @return ResponseEntity<byte[]>
     * @throws Exception
     */
    private ResponseEntity<byte[]> getTempFile() {
        RestTemplate rest = new RestTemplate();
        String url = environment.getProperty("static.path")+"/admin/business/integragood/IntegralCardVoucher.xls";
        String fileName = "integralCardVoucher-"+System.currentTimeMillis()+".xls";
        HttpEntity requestEntity = new HttpEntity(null,  new LinkedMultiValueMap<>());
        ResponseEntity<byte[]> exchange = rest.exchange(url, HttpMethod.GET, requestEntity, byte[].class);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<>( exchange.getBody(),headers, HttpStatus.OK);
    }
}
